package com.example.run_game;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;

import android.location.Location;
import android.os.Bundle;
import android.os.Parcelable;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMapOptions;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolylineOptions;

public class CustomMapFragment extends SupportMapFragment
	{
		private ArrayList<LatLng> markers;
		private LatLng centre;
		
		public static CustomMapFragment create(GoogleMapOptions options, ArrayList<Location> mMarkers, String chkFile) {
			CustomMapFragment fragment = new CustomMapFragment();

	        Bundle args = new Bundle();
	        args.putParcelable("MapOptions", options);
	        args.putParcelableArrayList("markers", mMarkers);
	        args.putString("checkpointfile", chkFile);
	        fragment.setArguments(args);

	        return fragment;
	    }

		@Override
		public void onCreate(Bundle savedInstanceState)
		{
			super.onCreate(savedInstanceState);
			
			ArrayList<Parcelable> l = getArguments().getParcelableArrayList("markers");
			markers = new ArrayList<LatLng>(l.size());
			double lat = 0;
			double lng = 0;
			System.out.println(l.size());
			for (Parcelable parcelable : l)
			{
				Location loc = (Location)parcelable;
				System.out.println(loc);
				lat += loc.getLatitude();
				lng += loc.getLongitude();
				markers.add(new LatLng(loc.getLatitude(),loc.getLongitude()));
			}
			centre = new LatLng(lat/l.size(), lng/l.size());
			System.out.println("Centre = " + centre.latitude + ", " + centre.longitude);
		}
		
		@Override
		public void onResume()
		{
			super.onResume();
			GoogleMap gMap = super.getMap();
			System.out.println(gMap);
			if (gMap != null)
			{
				gMap.setMyLocationEnabled(true);
				gMap.moveCamera(CameraUpdateFactory.newLatLng(centre));
				gMap.moveCamera(CameraUpdateFactory.zoomBy(15));
				PolylineOptions opt = new PolylineOptions();
				opt.addAll(markers);
				opt.width(3);
				gMap.addPolyline(opt);
				addCheckpoints(gMap);
			}
			else
				System.err.println("Error adding markers: gmap is null");
			
		}

		private void addCheckpoints(GoogleMap gMap)
		{
			String filename = getArguments().getString("checkpointfile");
			if (filename == null)
				return;
			FileInputStream f;
			try
			{
				f = getView().getContext().openFileInput(filename);
			} catch (FileNotFoundException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
				return;
			}
			int ch;
			StringBuffer input = new StringBuffer("");
			try
			{
				while ((ch = f.read()) != -1)
					input.append((char)ch);
				String[] checkpoints = input.toString().split("\n");
				int count = 1;
				for (String line : checkpoints)
				{
					System.out.println(line);
					String[] splitLine = line.split(" ");
					if (splitLine.length < 3)
						continue;
					MarkerOptions mo = new MarkerOptions();
					mo.draggable(false);
					mo.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW));
					mo.position(new LatLng(Double.parseDouble(splitLine[splitLine.length-2]), Double.parseDouble(splitLine[splitLine.length-1])));
					String title = "("+count+") ";
					count++;
					for (int i = 0; i < splitLine.length-2; i++)
						title += splitLine[i] + " ";
					mo.title(title);
					gMap.addMarker(mo);
				}
			} catch (IOException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}